package cn.ltpcloud.admin.web.service.impl;


import cn.ltpcloud.admin.web.service.UserService;
import cn.ltpcloud.common.entity.AjaxResult;
import cn.ltpcloud.common.pojo.auth.LoginUser;
import cn.ltpcloud.common.pojo.mapper.SysUserMapper;
import cn.ltpcloud.common.pojo.po.SysUser;
import cn.ltpcloud.common.utils.RedisUtils;
import com.baomidou.dynamic.datasource.annotation.Slave;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import static cn.ltpcloud.common.utils.ReqUtils.getLoginUser;
import static cn.ltpcloud.common.utils.ReqUtils.getUserId;

/**
 * @author jiejiebiezheyang
 * @since 2024-03-11 11:00
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private RedisUtils redisUtils;

    /**
     * 用户权限信息
     */
    @Override
    public Set<String> permissions(Integer userId) {
        Set<String> sysRoles = sysUserMapper.selectUserAllRole(userId);
        boolean hasSuper = sysRoles.contains("super");
        // 用户权限信息
        Set<String> permissions;
        if (hasSuper) {
            // 超级管理员所有权限
            permissions = sysUserMapper.selectAllPermission();
        } else {
            // 其他用户权限
            permissions = sysUserMapper.selectUserAllPermission(userId);
        }
        if (permissions == null || permissions.isEmpty()) {
            permissions = Collections.singleton("none");
        }
        return permissions;
    }

    /**
     * 用户信息
     */
    @Override
    public AjaxResult profiles() {
        Integer userId = getUserId();
        SysUser sysUser = sysUserMapper.selectById(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("id", sysUser.getId());
        map.put("username", sysUser.getUsername());
        map.put("nickname", sysUser.getNickname());
        //  刷新 并返回 权限
        Set<String> permissions = permissions(userId);
        LoginUser loginUser = getLoginUser();
        loginUser.setPermissions(permissions);
        long expire = redisUtils.getExpire("login:" + userId, TimeUnit.SECONDS);
        redisUtils.setCacheObject("login:" + userId, loginUser, expire, TimeUnit.SECONDS);
        map.put("permissions", permissions);
        return AjaxResult.success(map);
    }
}
